package cn.kooki.app.duobao.ui.Activity.Share;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.base.BaseRecyclerAdapter;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.Index.GoodsItem;
import cn.kooki.app.duobao.data.Bean.Index.IndexGoodResponse;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.share.NotShareGood;
import cn.kooki.app.duobao.data.Bean.share.NotShareResponse;
import cn.kooki.app.duobao.data.Bean.share.ShareListItem;
import cn.kooki.app.duobao.data.Bean.share.ShareResponse;
import cn.kooki.app.duobao.data.bus.AddShareListEvent;
import cn.kooki.app.duobao.data.bus.ChangePageEvent;
import cn.kooki.app.duobao.data.bus.OnRequestEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Activity.Comm.RootAcitivity;
import cn.kooki.app.duobao.ui.Activity.Goods.GoodsDetailAcitvity;
import cn.kooki.app.duobao.ui.Adapter.ListRecommAdapter;
import cn.kooki.app.duobao.ui.Adapter.MyShareAdapter;
import cn.kooki.app.duobao.ui.Adapter.ShareAdapter;
import cn.kooki.app.duobao.ui.view.CustomRefreshHeader;
import cn.kooki.app.duobao.ui.view.LoadMoreContainer;
import cn.kooki.app.duobao.ui.view.LoadMoreHandler;
import cn.kooki.app.duobao.ui.widget.ActionBarMenu;
import cn.kooki.app.duobao.ui.widget.CustomRelativeLayout;
import cn.kooki.app.duobao.ui.widget.XRecylerView;
import cn.kooki.app.duobao.util.ScreenUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.manager.AppManager;
import cn.kooki.app.duobao.util.manager.ShopCartManager;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/12/16.
 */
public class MyShareActivity extends BaseNavActivity implements View.OnClickListener {

    @Bind(R.id.share_title)
    TextView shareTitle;
    @Bind(R.id.blank_go_duobao)
    Button blankGoDuobao;
    @Bind(R.id.layout_empty)
    LinearLayout layoutEmpty;
    @Bind(R.id.list_recommend)
    RecyclerView listRecommend;
    @Bind(R.id.emptyWrapper)
    ScrollView emptyWrapper;
    @Bind(R.id.recycelerView)
    XRecylerView recycelerView;
    @Bind(R.id.loadingWrapper)
    CustomRelativeLayout loadingWrapper;
    private ActionBarMenu barMenu;
    private UserInfo userinfo;
    private ShareAdapter shareAdapter;
    private ArrayList<ShareListItem> datas = new ArrayList<>();
    private int page = 0;
    private ListRecommAdapter listRecommAdapter;

    private ArrayList<NotShareGood> goods = new ArrayList<>();
    private int refreshcount = 0;
    private MyShareAdapter adapter;

    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.blank_share_my_new);
        ButterKnife.bind(this);
    }


    @Override
    protected void afterView() {
        setTitle(R.string.title_activity_myshare);
        int size = ShopCartManager.getInstance().getCartsSize();
        if (size > 0) {
            topRefresh.setImageResource(R.drawable.ic_menu_overflow_withnew);
        } else {
            topRefresh.setImageResource(R.drawable.ic_menu_overflow);
        }
        topRefresh.setVisibility(View.VISIBLE);
        topRefresh.setOnClickListener(this);
        userinfo = SharePreferencesUtils.getUserinfo(this);
        loadingWrapper.showloading();
        emptyWrapper.setVisibility(View.GONE);
        blankGoDuobao.setOnClickListener(this);

        View listheader = LayoutInflater.from(this).inflate(R.layout.layout_myshare_header, recycelerView, false);
        recycelerView.addHeaderView(listheader);
        recycelerView.setLayoutManager(new LinearLayoutManager(this));
        recycelerView.setLoadingListener(new XRecylerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getdata(false);
            }

            @Override
            public void onLoadMore() {
                getdata(true);
            }
        });

        recycelerView.setLoadingMoreEnabled(true);
        listRecommend.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        listRecommAdapter = new ListRecommAdapter(this);
        listRecommend.setAdapter(listRecommAdapter);
        listRecommAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                GoodsItem item = (GoodsItem) data;
                Intent intent = new Intent(MyShareActivity.this, GoodsDetailAcitvity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("qishu", item.getQishu());
                startActivity(intent);
            }
        });
        adapter = new MyShareAdapter(this, datas, goods);
        adapter.setItemClickListener(new MyShareAdapter.OnTypeItemClickListener() {
            @Override
            public void onItemClick(int type, int position) {
                if (type == MyShareAdapter.GOOD_TYPE) {
                    intent(AddShareActivity.class, "item", goods.get(position));
                } else {
                    ShareListItem item = datas.get(position);
                    intent(ShareDetailActivity.class, "share_item", item);
                }
            }
        });
        recycelerView.setAdapter(adapter);
        gettuijian();
        getdata(false);

    }


    public void onEventMainThread(AddShareListEvent event) {
        getdata(false);
    }

    /**
     * 获取推荐商品
     */
    private void gettuijian() {
        MainFactory.getApiInstance().tuijianlist(new Callback<IndexGoodResponse>() {
            @Override
            public void success(IndexGoodResponse indexGoodResponse, Response response) {
                if (indexGoodResponse.getData() != null) {
                    listRecommAdapter.mDatas.clear();
                    listRecommAdapter.addDatas(indexGoodResponse.getData());
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private void getdata(final boolean isloadmore) {
        if (!isloadmore) {
            page = 0;
            refreshcount = 0;
        } else {
            page++;
        }

        if (!isloadmore) {
            MainFactory.getApiInstance().getRecordNotShare(userinfo.getUid(), new Callback<NotShareResponse>() {
                @Override
                public void success(NotShareResponse baseResponse, Response response) {
                    goods.clear();
                    refreshcount++;
                    if (baseResponse.data != null) {
                        goods.addAll(baseResponse.data);
                        if (refreshcount == 2) {
                            adapter.notifyDataSetChanged();
                        }
                    }
                    hiderefresh();
                    emptyWrapper.setVisibility(datas.size() + goods.size() == 0 ? View.VISIBLE : View.GONE);
                    recycelerView.setVisibility(datas.size() + goods.size() == 0 ? View.GONE : View.VISIBLE);
                }

                @Override
                public void failure(RetrofitError error) {
                    refreshcount++;
                    hiderefresh();
                    emptyWrapper.setVisibility(datas.size() + goods.size() == 0 ? View.VISIBLE : View.GONE);
                    recycelerView.setVisibility(datas.size() + goods.size() == 0 ? View.GONE : View.VISIBLE);
                }
            });
        }

        MainFactory.getApiInstance().getShareListMy(userinfo.getUid(), page, new Callback<ShareResponse>() {
            @Override
            public void success(ShareResponse baseResponse, Response response) {

                if (baseResponse.getData() != null) {
                    if (!isloadmore) {
                        refreshcount++;
                        datas.clear();
                        datas.addAll(baseResponse.getData());
                    } else {
                        datas.addAll(baseResponse.getData());
                    }
                    if (isloadmore || refreshcount == 2) {
                        adapter.notifyDataSetChanged();
                    }
                    if (baseResponse.getData().size() == Constants.DEFAULT_COUNT) {
                        recycelerView.restMoreLoading();
                    } else {
                        recycelerView.noMoreLoading();
                    }
                    hiderefresh();
                }
                emptyWrapper.setVisibility(datas.size() + goods.size() == 0 ? View.VISIBLE : View.GONE);
                recycelerView.setVisibility(datas.size() + goods.size() == 0 ? View.GONE : View.VISIBLE);
            }

            @Override
            public void failure(RetrofitError error) {
                if (!isloadmore) {
                    refreshcount++;
                }
                emptyWrapper.setVisibility(datas.size() + goods.size() == 0 ? View.VISIBLE : View.GONE);
                recycelerView.setVisibility(datas.size() + goods.size() == 0 ? View.GONE : View.VISIBLE);
            }
        });

    }

    private void hiderefresh() {
        if (refreshcount == 2) {
            recycelerView.refreshComplete();
            loadingWrapper.hideloading();
        }
    }


    @Override
    public void onClick(View v) {
        if (topRefresh == v) {
            showMenu();
        }
        if (v == blankGoDuobao) {
            EventBus.getDefault().post(new ChangePageEvent());
            AppManager.getAppManager().getTopWith(RootAcitivity.class);
        }
    }

    private void showMenu() {
        if (barMenu == null) {
            barMenu = new ActionBarMenu(this);
            barMenu.setActionMenuListener(new ActionBarMenu.ActionBarMenuClickListener() {
                @Override
                public void onItemClick(int index) {
                    ChangePageEvent pageEvent = new ChangePageEvent();
                    if (index == 0) {
                        pageEvent.item = 3;
                    } else {
                        pageEvent.item = 0;
                    }
                    EventBus.getDefault().post(pageEvent);
                    finish();
                }
            });
        }
        barMenu.showAsDropDown(topRefresh, -ScreenUtils.dpToPxInt(this, 80), 0);
    }


}
